package com.atguigu.teach.mytask;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyNumber{
    //资源类
    volatile int number=0;
    AtomicInteger atomicInteger=new AtomicInteger();

    public int getNumber() {
        return number;
    }
//1不加sychornize 会出错
    public synchronized void setNumber() {
        number++;
    }

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
        atomicInteger.getAndIncrement();
    }
}
public class MyCASDemo {
    public static void main(String[] args) {
//        AtomicInteger atomicInteger = new AtomicInteger(5);
//        System.out.println( atomicInteger.compareAndSet(5,1024)+"\t"+atomicInteger.get());
//        try {
//            TimeUnit.SECONDS.sleep(1);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println( atomicInteger.compareAndSet(1024,2021)+"\t"+atomicInteger.get());

        MyNumber myNumber = new MyNumber();
        for (int i = 0; i <200 ; i++) {
            new Thread(()->{
                for (int j = 0; j <200 ; j++) {
                    myNumber.setNumber();
                    myNumber.setAtomicInteger();
                }
            },String.valueOf(i)).start();
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"\t"+"---------最终结果"+myNumber.getNumber());
        System.out.println(Thread.currentThread().getName()+"\t"+"---------最终结果"+myNumber.getAtomicInteger().get());
    }
    
}
